package com.google.code.soumi.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.soumi.dao.Users;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SoumiService {

	private static SoumiService instance = null;
	private static SqlMapClient sqlMapClient; 
	
	
	/**
	 * 获取用户服务类
	 * @return
	 */
	public static synchronized SoumiService getInstance() {
		try {
			if (instance == null)
					instance = new SoumiService();
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	private SoumiService() throws Exception {
		sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(Resources.getResourceAsReader("com/google/code/soumi/dao/sqlmap-config.xml"));
	}
	
	
	/**
	 * 数据库操作对象
	 * @return
	 */
	public SqlMapClient getSqlMapClient(){
		return sqlMapClient;
	}
	

	/**
	 * 查询用户名
	 * 
	 * @param username
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Users> getUserList(String username) {
		try {
			List<Users> allUsers = new ArrayList<Users>();
			
			//查询CSDN用户
			List<Users> csdn = sqlMapClient.queryForList("getCsdnUsers", username);
			allUsers.addAll(csdn);
			
			//查询天涯用户
			List<Users> tianya = sqlMapClient.queryForList("getTianyaUsers", username);
			allUsers.addAll(tianya);

			
			//添加访问数和查询命中数
			sqlMapClient.startTransaction();
			sqlMapClient.update("increQueryCount");
			if(allUsers.size()>0)
				sqlMapClient.update("increHitCount");			
			sqlMapClient.commitTransaction();

			return allUsers;
		
		} catch (Exception e) {
			throw new RuntimeException("查询用户名出错", e);
		}finally{
			try {
				sqlMapClient.endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 获取访问总数
	 * @return
	 */
	public long getQueryCount(){
		try {
			long queryCount = (Long)sqlMapClient.queryForObject("getQueryCount");
			return queryCount;
		} catch (SQLException e) {
			throw new RuntimeException("获取访问总数出错", e);
		}
	}
	
	
	/**
	 * 获取命中数
	 * @return
	 */
	public long getHitCount(){
		try {
			long hitCount = (Long)sqlMapClient.queryForObject("getHitCount");
			return hitCount;
		} catch (SQLException e) {
			throw new RuntimeException("获取命中数出错", e);
		}
	}

}
